package servlet;

import dao.ArticleDao;
import dao.CategoryDao;
import dao.daoimpl.ArticleDaoImpl;
import dao.daoimpl.CategoryDaoImpl;
import bean.Category;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet(name="DeleteCategoryServlet",urlPatterns = "/DeleteCategoryServlet")
public class DeleteCategoryServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        int categoryId=Integer.parseInt(request.getParameter("deleteArticleCategoryId"));
        User user=(User)request.getSession().getAttribute("user");
        ArrayList<Category> categories=(ArrayList<Category>)request.getSession().getAttribute("userCategories");/*获取用户分类表列*/
        int flag=0;
        for(Category category:categories){
            if(category.getName().equals("默认")){
                flag=category.getId();
                break;
            }
        }
        CategoryDao categoryDao=new CategoryDaoImpl();
        ArticleDao articleDao=new ArticleDaoImpl();
        try {
            if(articleDao.updateDefaultCategory(articleDao.getCategoriesArticles(categoryId),flag)&&categoryDao.deleteCategory(categoryId)){
                System.out.println("用户删除目录成功");
                try {
                    request.getSession().setAttribute("userCategories",categoryDao.getCategories(user));
                    request.getSession().setAttribute("userArticles",articleDao.getArticles(user));
                }catch (SQLException sqlException) {
                    sqlException.printStackTrace();
                }
            }else{
                System.out.println("用户删除目录失败");
            }
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }
}
